package com.ccepc.algmanage.utils;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.IService;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * 常用工具类
 * Author: LuoLing
 */
@Slf4j
public class CommonUtils {

    /**
     * 将String类型转Json
     * @param jsonString 传入字符串
     * @return json对象
     */
    public static JSONObject stringToJson(String jsonString) {
        return JSONObject.parseObject(jsonString);
    }

    public static <T> int saveOrUpdateList(List<T> entityList, IService<T> service) {
        if (!entityList.isEmpty()) {
            if (getId(entityList.get(0)) == null) {
                entityList.forEach(entity -> {
                    setCreateTimestamp(entity, LocalDateTime.now());
                    setCreateUserId(entity, AuthInfoUtils.getUserId());
                    service.save(entity);
                });
                return 0;
            } else {
                entityList.forEach(entity -> {
                    setUpdateTimestamp(entity, LocalDateTime.now());
                    setUpdateUserId(entity, AuthInfoUtils.getUserId());
                    service.updateById(entity);
                });
                return 1;
            }
        }
        return -1;
    }

    /**
     * 新增或修改方法
     *
     * @param entity  实体类
     * @param service 对应Service
     * @param <T>     范形
     * @return 新增或修改结果
     */
    public static <T> int saveOrUpdate(T entity, IService<T> service) {
        setTenantId(entity, AuthInfoUtils.getTenantId());
        if (getId(entity) == null) {
            setCreateTimestamp(entity, LocalDateTime.now());
            setCreateUserId(entity, AuthInfoUtils.getUserId());
            if (service.save(entity)) {
                return 0;
            }
        } else {
            setUpdateTimestamp(entity, LocalDateTime.now());
            setUpdateUserId(entity, AuthInfoUtils.getUserId());
            if (service.updateById(entity)) {
                return 1;
            }
        }
        return -1;
    }

    private static <T> Integer getId(T entity) {
        try {
            return (Integer) entity.getClass().getMethod("getId").invoke(entity);
        } catch (Exception e) {
            log.error(e.getMessage());
            return null;
        }
    }

    private static <T> void setCreateTimestamp(T entity, LocalDateTime timestamp) {
        try {
            entity.getClass().getMethod("setCreatedTime", LocalDateTime.class).invoke(entity, timestamp);
        } catch (Exception e) {
            log.error(e.getMessage());
        }
    }

    private static <T> void setCreateUserId(T entity, Long userId) {
        try {
            entity.getClass().getMethod("setCreatedBy", Long.class).invoke(entity, userId);
        } catch (Exception e) {
            log.error(e.getMessage());
        }
    }

    private static <T> void setTenantId(T entity, Integer tenantId) {
        try {
            entity.getClass().getMethod("setTenantId", Integer.class).invoke(entity, tenantId);
        } catch (Exception e) {
            log.error(e.getMessage());
        }
    }

    private static <T> void setUpdateTimestamp(T entity, LocalDateTime timestamp) {
        try {
            entity.getClass().getMethod("setUpdatedTime", LocalDateTime.class).invoke(entity, timestamp);
        } catch (Exception e) {
            log.error(e.getMessage());
        }
    }

    private static <T> void setUpdateUserId(T entity, Long userId) {
        try {
            entity.getClass().getMethod("setUpdatedBy", Long.class).invoke(entity, userId);
        } catch (Exception e) {
            log.error(e.getMessage());
        }
    }

    /**
     * 将逗号隔开的字符串转换为long类型的数组
     * @param ids 逗号隔开的id字符串
     * @return long类型数组
     */
    public static List<Long> stringToLongArray(String ids) {
        String[] splits = ids.split(",");
        List<Long> res = new ArrayList<>();
        for(String s : splits) {
            res.add(Long.parseLong(s));
        }
        return res;
    }

    public static String initListString(String originS) {
        // 去除空格后的字符串，将中文逗号替换为英文逗号
        String newS = originS.replaceAll(" ", "");
        return newS.replaceAll("，", ",");
    }

    private static String getFileExtension(String fileName) {
        int dotIndex = fileName.lastIndexOf('.');
        if (dotIndex > 0 && dotIndex < fileName.length() - 1) {
            return fileName.substring(dotIndex + 1).toLowerCase();
        }
        return ""; // 如果没有后缀，则返回空字符串
    }

    public static boolean isImageFile(String fileName) {
        String fileExtension = getFileExtension(fileName);
        // 判断是否为图片类型的逻辑，可以根据常见图片格式的后缀来扩展
        return fileExtension.equals("jpg") || fileExtension.equals("jpeg") || fileExtension.equals("png");
    }

    public static boolean isVideoFile(String fileName) {
        String fileExtension = getFileExtension(fileName);
        // 判断是否为视频类型的逻辑，可以根据常见视频格式的后缀来扩展
        return fileExtension.equals("mp4") || fileExtension.equals("avi") || fileExtension.equals("mov");
    }

    public static JsonNode objectToJsonNode(Object object) {
        ObjectMapper objectMapper = new ObjectMapper();
        return objectMapper.valueToTree(object);
    }
}
